/*
	Copyright (c) 2011 Andrey O. Zbitnev (azbitnev@gmail.com)
	Licensed under the MIT License (LICENSE).

	$Id: ys.pane.js 21 2012-04-13 07:43:23Z azbitnev@gmail.com $

	version: 0.2pa

	required modules: core, mousewheel, slider
*/

(function ($) {

	$.ys.pane = {

		create: function (selector, options) {

			var defaults = {
			}

			var opts = $.extend(defaults, options);
			var $sel = $(selector)

			return $sel.each(function(i, el) {

				var $el = $(el), $cr = $el.children('.clip-rect'),
					$cc = $cr.children('div:eq(0)'),
					$vs = $('<div class="ys-scrollbar-vertical"/>').appendTo($el),
					$cl = $('<div class="clear"/>').appendTo($el),
					$hs = $('<div class="ys-scrollbar-horizontal"/>').appendTo($el)

				function sync() {

					var cw = $.ys.fn.width($cr), ch = $.ys.fn.height($cr),
						fw = $.ys.fn.width($cc), fh = $.ys.fn.height($cc)

					$hs.width(cw - $vs.outerWidth())
					$vs.height(ch - $hs.outerHeight())

					var $control = $vs.children('.thumb:eq(0)')
					if (!$control.data('ys-min-height'))
						$control.data('ys-min-height', $control.height())
					var h, minHeight = $control.data('ys-min-height')

					var top = $cr.scrollTop()
					h = (ch * $vs.innerHeight()) / fh
					$control.height(h < minHeight ? minHeight : h)
					$vs.val(top / (fh - ch))

					$vs.css({ display: (ch < fh ? 'block' : 'none') })

					var $control = $hs.children('.thumb:eq(0)')
					if (!$control.data('ys-min-width'))
						$control.data('ys-min-width', $control.width())
					var w, minWidth = $control.data('ys-min-width')

					var left = $cr.scrollLeft()
					w = (cw * $hs.innerWidth()) / fw
					$control.width(w < minWidth ? minWidth : w)
					$hs.val(left / (fw - cw))

					$hs.css({ display: (cw < fw ? 'block' : 'none') })
				}

				$.ys.slider.create($vs, {
					orientation: 'vertical',
					onchange: function (val, $slider) {
						$cr.scrollTop(($.ys.fn.height($cc) - $cr.innerHeight()) * val)
					}
				})

				$.ys.slider.create($hs, {
					orientation: 'horizontal',
					onchange: function (val, $slider) {
						$cr.scrollLeft(($.ys.fn.width($cc) - $cr.innerWidth()) * val)			
					}
				})

				$cc.bind('DOMSubtreeModified', function() {
					sync()
				})

				function scroll($sb, deltaY) {
					var val = $sb.val()
					if (deltaY < 0) {
						val += 0.05
					} else {
						val -= 0.05
					}
					if (val < 0) val = 0
					if (val > 1) val = 1
					$sb.val(val)
				}

				$cr.mousewheel(function (evt, delta, deltaX, deltaY) {
					scroll($vs, deltaY)
				})

				$vs.mousewheel(function (evt, delta, deltaX, deltaY) {
					scroll($vs, deltaY)
				})

				$hs.mousewheel(function (evt, delta, deltaX, deltaY) {
					scroll($hs, deltaY)
				})

				sync()
			})
		}
	}

})(jQuery);

